package smali

import java.io.File
import java.io.FileReader
import java.io.FileWriter

object SmaliClassUtil {

    private val matchClassRegex =
        """L[^->;"()\[\],:]+;""".toRegex()  //匹配用到的类 Lcom/combosdk/hotfix/HotfixModule;  Ljava/lang/String;


    /**
     * 寻找改smali引用的类名
     *  返回的形式 com/combosdk/hotfix/HotfixModule
     */
    fun findClass(smaliFile: String): HashSet<String> {
        val file = File(smaliFile)
        val hashSet = HashSet<String>()
        if (file.exists()) {
            val fileReader = FileReader(smaliFile)
            val readLines = fileReader.readLines()
            readLines.forEach { line ->
                val findAll = matchClassRegex.findAll(line)
                findAll.forEach {
                    it.groupValues.forEach {
                        val substring = it.substring(1, it.length - 1)
                        hashSet.add(substring)
                    }

                }

            }
        }

        return hashSet
    }


    /**
     *@param  smaliPath  smali相对路径  com/aaa/a.smali
     * 查找smali的路径
     */
    fun findSmaliPath(rootPath: String, smaliPath: String): String? {
        findClassesPath(rootPath).forEach {
            val file = File(it, smaliPath)
            if (file.exists()) {
                return file.absolutePath
            }
        }
        return null
    }

    private fun findClassesPath(rootPath: String): Set<String> {
        val set = HashSet<String>()
        var smaliFile = File("$rootPath/smali")
        var p = 1
        if (smaliFile.exists()) {
            set.add(smaliFile.absolutePath)
        }
        while (true) {
            p++
            smaliFile = File("$rootPath/smali_classes$p")
            if (smaliFile.exists()) {
                set.add(smaliFile.absolutePath)
            } else {
                break
            }
        }
        return set
    }


}
